/**
 *  *2010-4-10 上午01:22:09  add 
 */
package com.base.myproject.client.ui.celleditor;

import java.util.ArrayList;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.ColumnInfo;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.ui.BaseGrid;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.FieldEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.util.BaseEventPreview;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.util.Rectangle;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.StoreFilterField;
import com.extjs.gxt.ui.client.widget.form.TriggerField;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.user.client.Element;

/**
 * 多选对话框，格式如同“123;222;321”
 * @author Administrator
 *2010-4-10
 * javazgw@gmail.com
 */
public class MutiSelectEditor  extends TriggerField<String> implements
Listener<ComponentEvent>,FieldValue {
	final Window w = new Window();
	boolean b = false;
	List<ColumnConfig> columns = null;
	ModelType type = null;
	StoreInfo info = null;
	String returncolumn = null;
	BaseGrid<BusiObject> grid;
	BaseStore<BusiObject> basestore;
	BaseStore<BusiObject> target_store;
	ColumnInfo[] sourcecol;
	ColumnInfo[] target_col;
	public boolean isediting = false; //true 就是在编辑

	final Button yesbutton = new Button("确定");
	final Button button = new Button("取消");

	//MutiSelectEditor thiss;

	Object codevalue;
	Object displaynamevalue;
	String code;
	StoreFilterField<BusiObject> field ;
	Button reloadbutton = new Button("刷新");
	public MutiSelectEditor(List<ColumnConfig> columns, ModelType type,
			StoreInfo info, String returncolumn) {
		super();
		this.setTriggerStyle("x-form-search-trigger");
		this.columns = columns;
		this.type = type;
		this.info = info;
		this.returncolumn = returncolumn;
		//thiss = this;
		this.setEditable(false);
	}
	@Override
	protected void onBlur(ComponentEvent ce) {
		Rectangle rec = trigger.getBounds();
		if (rec.contains(BaseEventPreview.getLastClientX(), BaseEventPreview
				.getLastClientY())) {
			ce.stopEvent();
			return;
		}
		super.onBlur(ce);
		//focusPreview.remove();
	}
	@Override
	protected void onRender(Element target, int index) {
		
		super.onRender(target, index);
	}

	  private int lastKeyCode;
		protected void onKeyDown(FieldEvent fe) {
			super.onKeyPress(fe);
			lastKeyCode = fe.getKeyCode();

			if(lastKeyCode == KeyCodes.KEY_DELETE )
			{
				
				setValue(null);
				triggerBlur(null);
				
			}

			
		}
		

		  @Override
		  protected void onKeyPress(FieldEvent fe) {
			  super.onKeyPress(fe);
		    //char key = (char) fe.getKeyCode();
//		    System.out.println("lastKeyCode 2 = "+lastKeyCode);
//		    System.out.println("lastKeyCode 3 = "+ KeyCodes.KEY_DELETE);
		    if (fe.isSpecialKey(lastKeyCode) || lastKeyCode == KeyCodes.KEY_BACKSPACE
		        || lastKeyCode == KeyCodes.KEY_DELETE || fe.isControlKey()) {
		    	
		      return;
		    }
		    if (lastKeyCode == KeyCodes.KEY_ESCAPE) {
				w.hide();
			} else {
				showEditor();
			}
		
		    fe.stopEvent();
		  }

		@Override
		protected void onTriggerClick(ComponentEvent ce) {
			super.onTriggerClick(ce);
			// Info.display("Trigger Click", "TriggerClick is fired");
			
			showEditor();
		}

		private void showEditor() {
			if (!b) {
				initGrid();
				w.show();
				b = true;
			} else
				w.show();
			
			GWT.log("value="+getValue(),null);
			 List<BusiObject> sel = new ArrayList<BusiObject>();
			 
			 //设置选中状态
			 String[] value = null;
			 value=getValue()==null?null:getValue().split(";");
			 if(value!=null)
			 for(BusiObject bo:basestore.getModels())
			 {
				 for(String str:value)
				 {
					 if(str.equals(bo.get(returncolumn)))
					 {
						 sel.add(bo);
					 }
				 }
				 
			 }
			grid.getSelectionModel().select(sel, false);
			//grid.getSelectionModel().select(3, false);
			//for(g)
			//w.focus();
			field.reset();
			field.focus();
			//field.setEmptyText("请录入信息进行快速查找");
			
			isediting = true;
		}

		public boolean isshow() {
			return w.isVisible();
		}

		public void initGrid() {

			w.setHeading("选择");
			
			w.setModal(true);
			w.setSize(400, 480);
			w.setMaximizable(true);
	

			final CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
			columns.add(0, cbs.getColumn());


			ColumnModel cm = new ColumnModel(columns);

			/**
			 * 直接传入store，不需要加载数据，
			 */
			if(type!=null)
			basestore = new BaseStore(type, info);
			grid = new BaseGrid(basestore, cm,false,false,null);
			grid.setAutoWidth(true);
			grid.setAutoHeight(true);
			cbs.setSelectionMode(SelectionMode.MULTI);
			grid.setSelectionModel(cbs);
			
			// ---end grid
			ContentPanel bottompanel = new ContentPanel();
			bottompanel.setHeaderVisible(false);
			bottompanel.setLayout(new TableLayout(2));

			
			yesbutton.addListener(Events.Select, this);
			button.addListener(Events.Select, this);
			reloadbutton.addListener(Events.Select, this);
			// TableData t1 = new TableData();
			bottompanel.add(yesbutton);
			bottompanel.add(button);
			grid.setLoadMask(true);
			ContentPanel c = new ContentPanel();
			c.setHeaderVisible(false);
			//--加入过滤查找
			field = new StoreFilterField<BusiObject>() {
				@Override
				protected boolean doSelect(Store<BusiObject> store,
						BusiObject parent, BusiObject record, String property,
						String filter) {

				return	Select(store,parent,record,property,filter);
				}

				@Override
				protected void onFilter() {
					super.onFilter();

				
				}

			};
			
			field.setAutoWidth(true);
			field.setToolTip("对当前页面进行查找");
			field.bind(basestore);
			field.setFieldLabel("当页搜索");
			//--
			c.setLayout(new RowLayout(Orientation.VERTICAL));  
			
			ContentPanel cpanel = new ContentPanel();
			cpanel.setHeaderVisible(false);
			cpanel.setLayout(new RowLayout(Orientation.HORIZONTAL));
			reloadbutton.setToolTip("什么时候用此按钮？当你要选择的数据在别处被改变，点击刷新保持数据最新");
			if(this.type!=null)
			cpanel.add(field,new RowData(1, 1, new Margins(4)));
			
			cpanel.add(reloadbutton,new RowData(-1, 1, new Margins(4)));
			cpanel.setHeight(30);
			
			c.add(cpanel,new RowData(1, -1, new Margins(4)));
			c.add(grid,new RowData(1, 1, new Margins(4)));
			
			w.setScrollMode(Scroll.AUTO);
			w.add(c);
			w.addButton(yesbutton);
			w.addButton(button);
			// w.setBottomComponent(bottompanel);
			w.addListener(Events.Hide, this);
			w.show();
		}
		@Override
		public void setValue(String value) {

			super.setValue(value);
		}
	@Override
	public void handleEvent(ComponentEvent be) {

		if (be.getType() == Events.Select ||be.getType() == Events.Hide) {
			
			if (be.getSource() == yesbutton) {

				String revalue = "";
				for(BusiObject bo:grid.getSelectionModel().getSelectedItems())
				{
					revalue+=bo.get(returncolumn)+";";
				}
				if(revalue.equals(""))
					setValue(null);
				else
					setValue(revalue);

				if(code!=null)
				setCode(basestore.getValue(code));
				setDisplayname(basestore.getValue(returncolumn));
				
//				if (sourcecol!=null && sourcecol.length > 0) {
//					dopost(basestore.getAt(basestore.getCurcowindex()));
//				}
//				doposted(basestore.getAt(basestore.getCurcowindex()));
				
				isediting = false;
				w.hide();
				triggerBlur(null);
			} else if (be.getSource() == button) {

				isediting = false;
				w.hide();
				triggerBlur(null);
				// focus();
			}
			else if(be.getSource() == reloadbutton)
			{
				field.reset();
				basestore.reload();
			}
			
		}
		
		
		
		
	
	}

	@Override
	public Object getCode() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object getDisplayname() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setCode(Object code) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setDisplayname(Object displayname) {
		// TODO Auto-generated method stub
		
	}
	/**
	 * 过滤方法，有特殊的方式之类可以重载
	 * @param store
	 * @param parent
	 * @param record
	 * @param property
	 * @param filter
	 * @return
	 */
	protected boolean Select(Store<BusiObject> store,
			BusiObject parent, BusiObject record, String property,
			String filter) {
		for (int i = 0; i < type.getFieldCount(); i++) {

			Object name = record.get(type.getField(i).getName());
			
			//TODO
			if (name!=null&&(name.toString().indexOf(filter.toLowerCase()) != -1 || name.toString().indexOf(filter.toUpperCase()) != -1 )) {
				return true;
			}
		}
		return false;
	}
}
